{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "#####################################################################################################################################################################\n",
    "# xView2                                                                                                                                                            #\n",
    "# Copyright 2019 Carnegie Mellon University.                                                                                                                        #\n",
    "# NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING INSTITUTE MATERIAL IS FURNISHED ON AN \"AS-IS\" BASIS. CARNEGIE MELLON UNIVERSITY MAKES NO    #\n",
    "# WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR PURPOSE OR MERCHANTABILITY,          # \n",
    "# EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND WITH RESPECT TO FREEDOM FROM PATENT, # \n",
    "# TRADEMARK, OR COPYRIGHT INFRINGEMENT.                                                                                                                             #\n",
    "# Released under a MIT (SEI)-style license, please see LICENSE.md or contact permission@sei.cmu.edu for full terms.                                                 #\n",
    "# [DISTRIBUTION STATEMENT A] This material has been approved for public release and unlimited distribution.  Please see Copyright notice for non-US Government use  #\n",
    "# and distribution.                                                                                                                                                 #\n",
    "# This Software includes and/or makes use of the following Third-Party Software subject to its own license:                                                         #\n",
    "# 1. SpaceNet (https://github.com/motokimura/spacenet_building_detection/blob/master/LICENSE) Copyright 2017 Motoki Kimura.                                         #\n",
    "# DM19-0988                                                                                                                                                         #\n",
    "#####################################################################################################################################################################"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# To Run this notebook, start at the first cell with the license information and click run 4 times to show \n",
    "# the field blocks, then input the *full path* to the label, and image. Finally, click \"Create next input\", \n",
    "# you'll then see a full sized image with labels overlaid, you will also get different color labels if the\n",
    "# label file as damage labels under ['features']['xy'][i]['properties']['subtype'] where i is the polygon \n",
    "# in the ['xy'] list "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "hidden": true
   },
   "outputs": [],
   "source": [
    "from ipywidgets import Layout\n",
    "from IPython.display import Javascript, HTML\n",
    "import ipywidgets as widgets\n",
    "\n",
    "def run_all(ev):\n",
    "    display(Javascript('IPython.notebook.execute_cells_below()'))\n",
    "\n",
    "path_to_label = widgets.Text(\n",
    "    placeholder='Label path here',\n",
    "    description='Label:',\n",
    "    disabled=False,\n",
    "    layout=Layout(width='100%')\n",
    ")\n",
    "path_to_image = widgets.Text(\n",
    "    placeholder='Image path here',\n",
    "    description='Image:',\n",
    "    disabled=False,\n",
    "    layout=Layout(width='100%')\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<script>\n",
       "code_show=true; \n",
       "function code_toggle() {\n",
       " if (code_show){\n",
       " $('div.input').hide();\n",
       " } else {\n",
       " $('div.input').show();\n",
       " }\n",
       " code_show = !code_show\n",
       "} \n",
       "$( document ).ready(code_toggle);\n",
       "</script>\n",
       "The raw code for this IPython notebook is by default hidden for easier reading.\n",
       "To toggle on/off the raw code, click <a href=\"javascript:code_toggle()\">here</a>."
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\n",
    "HTML('''<script>\n",
    "code_show=true; \n",
    "function code_toggle() {\n",
    " if (code_show){\n",
    " $('div.input').hide();\n",
    " } else {\n",
    " $('div.input').show();\n",
    " }\n",
    " code_show = !code_show\n",
    "} \n",
    "$( document ).ready(code_toggle);\n",
    "</script>\n",
    "The raw code for this IPython notebook is by default hidden for easier reading.\n",
    "To toggle on/off the raw code, click <a href=\"javascript:code_toggle()\">here</a>.''')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/javascript": [
       "IPython.notebook.execute_cells_below()"
      ],
      "text/plain": [
       "<IPython.core.display.Javascript object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "d2be852d23c1454ca6d8b7871ecf5eb5",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Text(value='/tmp/inference/inference.json', description='Label:', layout=Layout(width='100%'), placeholder='La…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "a4df1b7f08c6433eaba706e160b7956b",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Text(value='/Users/rthosfelt/Downloads/xBD/tuscaloosa-tornado/images/tuscaloosa-tornado_00000027_pre_disaster.…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "1bcd23b318194309bcee1c297b83c4c2",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Button(description='Create next input', style=ButtonStyle())"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "4df43ae86c7847c595ef8deab722b358",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Text(value='', description='Label:', layout=Layout(width='100%'), placeholder='Label path here')"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "6d55945ff4664d3bb3341993e0df13f7",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Text(value='', description='Image:', layout=Layout(width='100%'), placeholder='Image path here')"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "9fa49996441e4368bb3c477207577b08",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Button(description='Create next input', style=ButtonStyle())"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "display(path_to_label, path_to_image)\n",
    "button = widgets.Button(description=\"Create next input\")\n",
    "button.on_click(run_all)\n",
    "display(button)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json \n",
    "from PIL import Image, ImageDraw\n",
    "from IPython.display import display\n",
    "from shapely import wkt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "ename": "FileNotFoundError",
     "evalue": "[Errno 2] No such file or directory: ''",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mFileNotFoundError\u001b[0m                         Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-7-bcee7cd74b40>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m      3\u001b[0m \u001b[0mpath_to_image_value\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mpath_to_image\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mvalue\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      4\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0;32mwith\u001b[0m \u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mpath_to_label_value\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'rb'\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mimage_json_file\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      6\u001b[0m     \u001b[0mimage_json\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mjson\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mload\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mimage_json_file\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: ''"
     ]
    }
   ],
   "source": [
    "# Opening and loading polygons from label json \n",
    "path_to_label_value = path_to_label.value\n",
    "path_to_image_value = path_to_image.value\n",
    "\n",
    "with open(path_to_label_value, 'rb') as image_json_file:\n",
    "    image_json = json.load(image_json_file)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "coords = image_json['features']['xy']\n",
    "wkt_polygons = []\n",
    "\n",
    "for coord in coords:\n",
    "    if 'subtype' in coord['properties']:\n",
    "        damage = coord['properties']['subtype']\n",
    "    else:\n",
    "        damage = 'no-damage'\n",
    "    wkt_polygons.append((damage, coord['wkt']))\n",
    "    \n",
    "polygons = []\n",
    "\n",
    "for damage, swkt in wkt_polygons:\n",
    "    polygons.append((damage, wkt.loads(swkt)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "# Loading image\n",
    "img = Image.open(path_to_image_value)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "draw = ImageDraw.Draw(img, 'RGBA')\n",
    "\n",
    "damage_dict = {\n",
    "    \"no-damage\": (0, 255, 0, 100),\n",
    "    \"minor-damage\": (0, 0, 255, 125),\n",
    "    \"major-damage\": (255, 69, 0, 125),\n",
    "    \"destroyed\": (255, 0, 0, 125),\n",
    "    \"un-classified\": (255, 255, 255, 125)\n",
    "}\n",
    "\n",
    "for damage, polygon in polygons:\n",
    "    x,y = polygon.exterior.coords.xy\n",
    "    coords = list(zip(x,y))\n",
    "    draw.polygon(coords, damage_dict[damage])\n",
    "\n",
    "del draw\n",
    "\n",
    "display(img)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
